<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\BaseController;
use app\index\model\Limit;
use app\index\model\Order;
use app\index\model\Product;
use app\index\model\ShoppingChar;
use code\QRcode;
use pay\WxPay;
use think\cache\driver\Redis;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class Good extends BaseController
{
    private $echostr;
    private $arr;
    //购物车
    public function cart()
    {
        if(Session::get('user')==null){
            return redirect('../cate/category');
        }
        $list = ShoppingChar::cartList();
        View::assign('list',$list);
        return View::fetch();
    }
    public function cartAdd()
    {
        $post = Request::post();
        $data = [
            'id'=>$post['id'],
            'num'=>$post['num']+1,
        ];
        try{
            $res = ShoppingChar::update($data);
        }catch (\Exception $e){
            echo $e->getMessage();
            $res = $e->getMessage();
        }
        return json($res);
    }
    public function cartAddj()
    {
        $post = Request::post();
        $data = [
            'id'=>$post['id'],
            'num'=>$post['num']-1,
        ];
        try{
            $res = ShoppingChar::update($data);
        }catch (\Exception $e){
            echo $e->getMessage();
            $res = $e->getMessage();
        }
        if ($data['num']<1){
            ShoppingChar::destroy($data['id']);
        }
        return json($res);
    }
    public function cartDel()
    {
        $post = Request::post();
        ShoppingChar::destroy($post['id']);
    }
    public function cartDelAll()
    {
        $id = ShoppingChar::where('uid','=',Session::get('user'))->column('id');
        ShoppingChar::destroy($id);
    }

    public function ajaxCart()
    {
        $post = Request::post();
        if (Request::isPost()){
            $gid = $post['gid'];
            $find = ShoppingChar::where('pid','=',$gid)->where('uid','=',Session::get('user'))->find();
            if (isset($find) && !empty($find)){
                $num = $find['num']+1;
                $edit=[
                    'id'=>$find['id'],
                    'num'=>$num
                ];
                try{
                    $res = ShoppingChar::where('uid','=',Session::get('user'))->where('pid','=',$gid)->update($edit);
                }catch (\Exception $e){
                    echo $e->getMessage();
                    $res = false;
                }
            }else{
                $gid = $post['gid'];
                $line = Product::field('id,price_shop')->where('id','=',$gid)->find()->toArray();
                $add = [
                    'uid'=>Session::get('user'),
                    'pid'=>$line['id'],
                    'price'=>$line['price_shop'],
                    'num'=>1,
                    'addtime'=>time()
                ];
                try{
                    $res = ShoppingChar::create($add);
                }catch (\Exception $e){
                    echo $e->getMessage();
                    $res = false;
                }
            }
        }
        return $res;
    }
    //支付页
    public function buy()
    {
        $get = Request::get();
        $line = Order::where('order_sn','=',$get['sn'])->find()->toArray();
        View::assign('line',$line);
        return View::fetch();
    }
    //二维码
    public function ajaxBuy()
    {
        $post = Request::post();
        $order = Order::where('order_sn','=',$post['order'])->find()->toArray();
        $url = "http://shop.fzyhh.top/index.php/index/Good/getNotice";
        $pay = new WxPay($url);
        $rt = $pay->prepay("","{$order['order_sn']}",0.01,"买卖","NATIVE");
        $code_url = $rt['code_url'];
        QRcode::png($code_url);
        $img = base64_encode(ob_get_contents());
        ob_end_clean();
        return $img;
    }
    public function ajaxSuccess()
    {
        $post = Request::post();
        $order = Order::where('order_sn','=',$post['order'])->find()->toArray();
        $url = "http://shop.fzyhh.top/index.php/index/Good/getNotice";
        $pay = new WxPay($url);
        $rt = $pay->queryPay("{$order['order_sn']}");
        if (isset($rt) && !empty($rt)){
            if ($rt['trade_state']=="SUCCESS"){
                $edit = [
                    'id'=>$order['id'],
                    'pay_sn'=>$rt['transaction_id'],
                    'status'=>11
                ];
                Order::update($edit);
                $arr = ["status"=>"1","msg"=>"支付成功"];
                echo json_encode($arr);
            }elseif ($rt['trade_state']=="PAYERROR"){
                $arr = ["status"=>"2","msg"=>"支付失败"];
                echo json_encode($arr);
            }
        }
    }

    public function getNotice()
    {
        $xml = file_get_contents("php://input");//接受Xml包
        Log::record($xml);

    }
    //秒杀商品详情页
    public function goodLimit()
    {
        $get = Request::get();
        $list = \app\index\model\Address::addressList();
        View::assign('list',$list);
        $line = Limit::alias('l')
            ->where('l.id','=',$get['id'])
            ->field('l.*')
            ->find()->toArray();
        $line['amount'] = $line['price']*$line['num'];
        View::assign('line',$line);
        return View::fetch();
    }
    //秒杀支付跳转
    public function ajaxlimit()
    {
        $post = Request::post();
        $this->redis->auth('123456');
        if($this->redis->llen("{$post['pid']}")<1){
            return false;
        }
        $address = \app\index\model\Address::where('uid','=',\session('user'))->where('is_default','=',1)->find();
        $data = [
            'order_sn'=>date('YmdHid',time()),
            'uid'=>Session::get('user'),
            'aname'=>$address['name'],
            'atel'=>$address['tel'],
            'asheng'=>$address['sheng'],
            'acity'=>$address['city'],
            'aquyu'=>$address['quyu'],
            'address'=>$address['address'],
            'price'=>$post['price'],
            'addtime'=>time(),
            'status'=>11
        ];
        // 启动事务
        Db::startTrans();
        try{
            $add = Order::insertGetId($data);
            $res = Order::suffix('_product')
                ->insert(['pid'=>$post['pid'],'order_id'=>$add,'price'=>$post['price'],'num'=>1,'addtime'=>time()]);
            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            $add = false;
            // 回滚事务
            Db::rollback();
        }
        if ($add){
            return $add;
        }else{
            return false;
        }
    }

    //商品详情页
    public function goodsInfo()
    {
        $get = Request::get();
        $find = Product::goodsInfoList($get);
        $find['photo_string'] = explode(',',$find['photo_string']);
        $attr = Product::ProductAttr($find['id']);
        View::assign('attr',$attr);
        View::assign($find);
        return View::fetch();
    }
    //确认订单页
    public function order()
    {
        $get = Request::get();
        $list = \app\index\model\Address::addressList();
        View::assign('list',$list);
        $line = ShoppingChar::alias('sc')
            ->where('sc.id','in',$get['id'])
            ->field('sc.*,p.photo_x,p.name')
            ->join('product p','p.id=sc.pid')
            ->select()->toArray();
        $amount = [];
        foreach ($line as &$v){
            $v['amount'] = $v['price']*$v['num'];
            $amount[] = $v['amount'];
            $amounts = array_sum($amount);
        }
        View::assign('amounts',$amounts);
        View::assign('line',$line);
        return View::fetch();
    }
    //添加订单
    public function userAdd()
    {
        $redis = new Redis();
        $redis->connect('127.0.0.1',6379);
        $redis->auth('123456');
        $post = Request::post();
        $get = Request::get();
        $id = explode(',',$get['id']);
        if (empty($post['aid'])){
            $this->error('请选择收获地址');
        }else{
            $address = \app\index\model\Address::where('id','=',$post['aid'])->find()->toArray();
        }
        if ($redis->llen("{$get['id']}")>0){//判断redis数据库是否有该商品
            if ($redis->llen("{$get['id']}")<1){//如果改商品数量小于1
                $this->error('商品售空');
            }else{
                $open_id = Db::name('user')->where('id','=',Session::get('user'))->value('openid');
                if ($redis->get($get['id'].$open_id)){
                    $this->error('已购买该商品');
                }else{
                    $redis->lpop("{$get['id']}");
                    $redis->set($get['id'].$open_id,$get['id'].$open_id);
                }
            }
        }

        $data = [
            'order_sn'=>date('YmdHid',time()),
            'uid'=>Session::get('user'),
            'aname'=>$address['name'],
            'atel'=>$address['tel'],
            'asheng'=>$address['sheng'],
            'acity'=>$address['city'],
            'aquyu'=>$address['quyu'],
            'address'=>$address['address'],
            'price'=>$post['amount'],
            'amount'=>$post['amount'],
            'addtime'=>time(),
            'status'=>10
        ];
        // 启动事务
        Db::startTrans();
        try{
            $add = Order::insertGetId($data);
            foreach ($post['gname'] as $k=>$v){
                $res = Order::suffix('_product')
                    ->insert(['pid'=>$post['pid'][$k],'order_id'=>$add,'name'=>$v,'price'=>$post['price'][$k],'num'=>$post['num'][0],'addtime'=>time()]);
            }
            // 提交事务
            Db::commit();
        }catch (\Exception $e){
            $add = false;
            // 回滚事务
            Db::rollback();
        }

        if ($add){
            ShoppingChar::destroy($id);
            $this->success('成功',url('Good/buy',['sn'=>$data['order_sn']]));
        }else{
            $this->error('失败');
        }

    }





}